import { asyncRouterMap, constantRouterMap } from '@/router'
import user from './user'
import Layout from '@/views/layout/Layout'
const _import = require('@/router/_import_' + process.env.NODE_ENV)

// 利用权限信息构建路由信息
function buildAsyncRouter(datasource) {
  const { permissions = [], path = [], level = 1 } = datasource
  if (!permissions) {
    return []
  }
  const routers = []
  for (let i = 0; i < permissions.length; i++) {
    const item = permissions[i]
    if (item.name) {
      const currentPath = path.concat([item.name])
      const router = {
        path: item.name,
        name: currentPath.join('_'),
        meta: { title: item.title },
        hidden: item.hidden || false
      }
      if (level === 1) {
        router.meta.icon = 'component'
        router.component = Layout
        router.path = '/' + router.path
      } else {
        router.component = _import(currentPath.join('/'))
      }
      if (item.children && item.children.length > 0) {
        router.children = buildAsyncRouter({ permissions: item.children, path: currentPath, level: level + 1 })
        // router.path = '/' + router.path
        router.redirect = router.path + '/' + router.children[0].path
      }
      routers.push(router)
    }
  }
  return routers
}

const permission = {
  state: {
    routers: constantRouterMap,
    addRouters: []
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers
      state.routers = constantRouterMap.concat(routers)
    }
  },
  actions: {
    GenerateRoutes({ commit }) {
      return new Promise(resolve => {
        const accessedRouters = buildAsyncRouter({ permissions: user.state.permissions }).concat(asyncRouterMap)
        commit('SET_ROUTERS', accessedRouters)
        resolve()
      })
    }
  }
}

export default permission
